<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>复制粘贴元素</title>
</head>
<body>

  <div>
    <button onclick="copy()">复制</button>
    <button onclick="paste()">粘贴</button>
  </div>
  <canvas id="c" width="500" height="400" style="border: 1px solid #ccc;"></canvas>

  <script src="../../script/fabric.js"></script>
  <script>
    // 官方demo地址：http://fabricjs.com/copypaste


    const canvas = new fabric.Canvas('c')

    let rect1 = new fabric.Rect({
      left: 100,
      top: 50,
      fill: '#D81B60',
      width: 100,
      height: 100,
      strokeWidth: 2,
      stroke: "#880E4F",
      rx: 10,
      ry: 10,
      angle: 45,
      hasControls: true
    })

    let rect2 = new fabric.Rect({
      left: 200,
      top: 50,
      fill: '#F06292',
      width: 100,
      height: 100,
      strokeWidth: 2,
      stroke: "#880E4F",
      rx: 10,
      ry: 10,
      angle: 45,
      hasControls: true
    })

    var circle1 = new fabric.Circle({
      radius: 65,
      fill: '#039BE5',
      left: 0
    })

    var circle2 = new fabric.Circle({
      radius: 65,
      fill: '#4FC3F7',
      left: 110,
      opacity: 0.7
    })

    var group = new fabric.Group([circle1, circle2, ], {
      left: 40,
      top: 250
    })

    canvas.add(rect1, rect2, group)

    let _clipboard = null

    function copy() {
      let target = canvas.getActiveObject()
      if (target) {
        target.clone(function(cloned) {
          _clipboard = cloned
        })
      }
    }

    function paste() {
      if (!_clipboard) return

      canvas.discardActiveObject()
      _clipboard.clone(function(clonedObj) {
        clonedObj.set({
          left: clonedObj.left + 10,
          top: clonedObj.top + 10,
          evented: true, // 当设置为“ false”时，对象不能成为事件的目标。所有事件都会通过它传播。
        })

        if (clonedObj.type === 'activeSelection') {
          clonedObj.canvas = canvas
          clonedObj.forEachObject(function(obj) {
            canvas.add(obj)
          })
          clonedObj.setCoords()
        } else {
          canvas.add(clonedObj)
        }

        _clipboard.top += 10
        _clipboard.left += 10
        canvas.setActiveObject(clonedObj)
        canvas.requestRenderAll()
      })
    }
  </script>
</body>
</html>